package com.dmooo.ymx.activity;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dmooo.ymx.R;
import com.dmooo.ymx.adapter.MerchantAdminListAdapter;
import com.dmooo.ymx.base.BaseActivity;
import com.dmooo.ymx.bean.MerchantAdminListBean;
import com.dmooo.ymx.common.LogUtils;
import com.dmooo.ymx.common.SPUtils;
import com.dmooo.ymx.config.Constants;
import com.dmooo.ymx.https.HttpUtils;
import com.dmooo.ymx.login.LoginActivity;
import com.dmooo.ymx.mallbean.AddressBean;
import com.dmooo.ymx.mallbean.ShopMallGoodsBean;
import com.dmooo.ymx.utils.RecycleViewDivider;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

/**
 * 客服
 */
public class MerchantAdminListActivity extends BaseActivity {
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refresh)
    SmartRefreshLayout refresh;
    private List<MerchantAdminListBean.Item> list=new ArrayList<>();
    private MerchantAdminListAdapter merchantAdminListAdapter;

    @Override
    protected void initUI() {
        setContentView(R.layout.activity_merchant_admin_list);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    @Override
    protected void initData() {
        txtTitle.setText("客服");
        refresh.setEnableLoadMore(false);
        refresh.setEnableRefresh(false);
        getList();
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        merchantAdminListAdapter=new MerchantAdminListAdapter(R.layout.item_merchant_admin,list);
        recyclerview.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL));
        recyclerview.setAdapter(merchantAdminListAdapter);
        merchantAdminListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle=new Bundle();
                bundle.putString("name",list.get(position).service_nickname);
                bundle.putString("uuid","kf_3");
                bundle.putString("image",Constants.APP_IP+list.get(position).avatar);
                bundle.putString("msg",getIntent().getExtras().getString("msg"));
                openActivity(ChatActivity.class,bundle);
            }

        });

//        EMClient.getInstance().login("user" + SPUtils.get(this, Constants.UID, "").toString(), "123456", new EMCallBack() {//回调
//            @Override
//            public void onSuccess() {
//                EMClient.getInstance().groupManager().loadAllGroups();
//                EMClient.getInstance().chatManager().loadAllConversations();
//                Log.d("main", "登录聊天服务器成功！");
//                SPUtils.put(MerchantAdminListActivity.this, "new", "1");
////                finish();
//            }
//
//            @Override
//            public void onProgress(int progress, String status) {
//
//            }
//
//            @Override
//            public void onError(int code, String message) {
//                Log.d("main", "登录聊天服务器失败！" + code + "  " + message);
//                if(message.contains("already login")){
//                    EMClient.getInstance().logout(true);
//                }else{
//                    handler.sendEmptyMessage(0);
//                }
//            }
//        });

    }

//    private void loginHuanxin() {
//        try{
//            EMClient.getInstance().login(""+SPUtils.getStringData(MerchantAdminListActivity.this, "uid", ""), "123456", new EMCallBack() {//回调
//                @Override
//                public void onSuccess() {
//                    EMClient.getInstance().groupManager().loadAllGroups();
//                    EMClient.getInstance().chatManager().loadAllConversations();
//                    Log.d("main", "登录聊天服务器成功！");
//                    SPUtils.put(MerchantAdminListActivity.this, "new", "1");
////                    finish();
//                }
//
//                @Override
//                public void onProgress(int progress, String status) {
//
//                }
//
//                @Override
//                public void onError(int code, String message) {
//                    if(message.contains("already login")){
//                        EMClient.getInstance().logout(true);
//                    }else{
//                        handler.sendEmptyMessage(0);
//                    }
////                    showToast("登录聊天服务器失败");
//                    Log.d("main", "登录聊天服务器失败！" + code+"  "+message);
//                }
//            });
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//
//    }

//    private Handler loginHandle=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            loginHuanxin();
//        }
//    };
//    private Handler handler=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            createChat();
//        }
//    };

//    private void createChat() {
//        RequestParams params = new RequestParams();
//        params.put("token", SPUtils.get(this, Constants.TOKEN, "").toString());
//        HttpUtils.post(Constants.APP_IP+"/app.php?c=Huanxin&a=createUser", params, new TextHttpResponseHandler() {
//            @Override
//            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
//                // 输出错误信息
//                LogUtils.e(TAG, "onFailure()--" + responseString);
//            }
//
//            @Override
//            public void onFinish() {
//                // 隐藏进度条
//                super.onFinish();
//                closeLoadingDialog();
//            }
//
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, String responseString) {
//                try {
//                    JSONObject jsonObject = new JSONObject(responseString);
//                    loginHandle.sendEmptyMessage(0);
////                    //返回码
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//
//            @Override
//            public void onStart() {
//                // 显示进度条
//                super.onStart();
//                showLoadingDialog();
//            }
//        });
//    }


    @Override
    protected void initListener() {

    }

    private void getList(){
        Map<String,Object> map=new HashMap<>();
        RequestParams params = new RequestParams();
        params.put("merchant_id",getIntent().getExtras().getString("merchant_id"));
        params.put("p",1);
        params.put("per",20);
        HttpUtils.post(Constants.APP_IP+"/app.php?c=MerchantAdmin&a=getList", params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // 输出错误信息
                LogUtils.e(TAG, "onFailure()--" + responseString);
            }

            @Override
            public void onFinish() {
                // 隐藏进度条
                super.onFinish();
                closeLoadingDialog();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    JSONObject jsonObject = new JSONObject(responseString);
                    GsonBuilder builder=new GsonBuilder();
                    builder.serializeNulls();
                    try {
                        final JSONArray array = jsonObject.getJSONObject("data").getJSONArray("list");
                        Gson gson=builder.create();
                        for (int i = 0; i < array.length(); i++) {
                            if("3".equals(array.getJSONObject(i).getString("id"))){
                                list.add(gson.fromJson(array.getJSONObject(i).toString(), MerchantAdminListBean.Item.class));
                            }
                        }
                        merchantAdminListAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStart() {
                // 显示进度条
                super.onStart();
                showLoadingDialog();
            }
        });
    }

    @OnClick(R.id.txt_back)
    public void onViewClicked() {
        finish();
    }
}
